

#import "EditViewController.h"
#import "ImgCell.h"
#import "TextEditViewController.h"
#import "ColorEditViewController.h"
@interface EditViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (strong, nonatomic) IBOutlet UIView *toolbar;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *toolbarBottom;
@property (strong, nonatomic) IBOutlet UITextView *input;
@property (strong, nonatomic) IBOutlet UILabel *plachholder;
@property (strong, nonatomic) IBOutlet UICollectionView *collection;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *input1H;
@property (strong, nonatomic) IBOutlet UITextField *input1;
@property (strong, nonatomic) IBOutlet UIButton *editBtn;

@end

@implementation EditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self updateUI];
}
- (void)initUI{
    self.title = self.model.name;
    self.editBtn.selected = self.model.name.length <= 0;
    NSString *icon = self.model.name.length > 0 ? @"删除":@"勾";
    [self.rightBtn setImage:[UIImage imageNamed:icon] forState:UIControlStateNormal];
    [self.collection registerNib:[ImgCell nib] forCellWithReuseIdentifier:[ImgCell ID]];
}
- (void)updateUI{
    self.input1H.constant = self.editBtn.selected ? 34 : 0;
    self.input1.hidden = self.editBtn.selected == NO;
    self.input.text = self.model.content;
    self.input.textHexColor = self.model.textColor;
    self.input.font = [UIFont systemFontOfSize:self.model.font];
    self.input.bgHexColor = self.model.bgColor;
    self.input1.text = self.model.content;
    self.input1.textHexColor = self.model.textColor;
    self.input1.font = [UIFont systemFontOfSize:self.model.font];
    self.input1.bgHexColor = self.model.bgColor;
    self.collection.bgHexColor = self.model.bgColor;
    self.view.bgHexColor = self.model.bgColor;
    self.plachholder.hidden = self.model.content.length > 0;
    self.input.userInteractionEnabled = self.editBtn.selected;
    self.input1.enabled = self.editBtn.selected;
    [self.collection reloadData];
}

- (void)rightBtnAction{
    if (self.model.content.length <= 0) {
        return [CCHud msg:LS(@"内容不能为空")];
    }else if (self.model.imgs.count <= 0){
        return [CCHud msg:LS(@"至少选择一张图片")];
    }else if (self.model.name <= 0){
        return [CCHud msg:LS(@"植物名称不能空")];
    }
    if (self.model.account.length <= 0) {
        self.model.account = APP.user.account;
        [PlantTool update:self.model complete:^(BOOL success) {
            [self backBtnAction];
        }];
        return;
    }
    [PlantTool delete:self.model complete:^(BOOL success) {
        [self backBtnAction];
    }];
    
    
}
- (IBAction)actionForBtn:(UIButton *)sender {
    WS(self)
    if (sender.tag != 202 && self.editBtn.selected == NO) {
        return;
    }
    if (sender.tag == 201) {
        TextEditViewController *vc = [TextEditViewController new];
        vc.fontBlock = ^(CGFloat font) {
            weakself.model.font = font;
            [weakself updateUI];
        };
        vc.colorBlock = ^(NSString * _Nonnull color) {
            weakself.model.textColor = color;
            [weakself updateUI];
        };
        [self presentViewController:vc animated:NO completion:nil];
    }else if (sender.tag == 203){
        SheetViewController *sheetvc = [SheetViewController new];
        sheetvc.withCancel = NO;
        sheetvc.array = @[@"拍摄",@"相册",@"取消"];
        WS(sheetvc)
        sheetvc.block = ^(int index, NSString * _Nonnull text) {
            if ([text isEqualToString:LS(@"取消")]) {
                return [weaksheetvc dismissViewControllerAnimated:NO completion:nil];
            }
            NSString *mediaType = AVMediaTypeVideo; //读取媒体类型
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType]; //读取设备授权状态
            if (authStatus == AVAuthorizationStatusNotDetermined || authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) { // 授权受阻
                UIAlertController *alterCon = [UIAlertController alertControllerWithTitle:LS(@"是否开启相机访问权限？")
                                                                                  message:nil
                                                                           preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *OFF = [UIAlertAction actionWithTitle:LS(@"取消") style:UIAlertActionStyleDefault handler:nil];
                UIAlertAction *ON = [UIAlertAction actionWithTitle:LS(@"确定") style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { // 设置权限
                    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    if ([[UIApplication sharedApplication] canOpenURL:url]) {
                        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                            // do something
                        }];
                    }
                }];
                [alterCon addAction:OFF];
                [alterCon addAction:ON];
                [self presentViewController:alterCon animated:YES completion:nil];
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [CCHud startHud];
                });
                UIImagePickerController *vc = [UIImagePickerController new];
                vc.delegate = weakself;
                vc.allowsEditing = YES;
                vc.sourceType = index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
                vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
                [[weakself currentVC] presentViewController:vc animated:YES completion:^{
                    [CCHud stopHud];
                }];
            }
        };
        [[weakself currentVC] presentViewController:sheetvc animated:NO completion:nil];
    }else if (sender.tag == 202){
        sender.selected = !sender.selected;
        [self updateUI];
    }
}
-(Plant *)model{
    if (!_model) {
        _model = [Plant new];
    }
    return _model;
}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    UIImage *img = info[UIImagePickerControllerEditedImage];
    NSData *data = UIImageJPEGRepresentation(img, 0.5);
    if (self.model) {
        [self.model.imgs addObject:data];
    }
    [self updateUI];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UITextViewDelegate
- (void)textFieldDidChangeSelection:(UITextField *)textField{
    self.model.name = textField.text;
}
#pragma mark - UITextViewDelegate
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    self.plachholder.hidden = YES;
    return YES;
}
- (void)textViewDidChange:(UITextView *)textView{
    self.model.content = textView.text;
    self.plachholder.hidden = textView.text.length > 0;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.model.imgs.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ImgCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[ImgCell ID] forIndexPath:indexPath];
    cell.img.image = [UIImage imageWithData:self.model.imgs[indexPath.row]];
    WS(self)
    cell.block = ^{
        if (self.editBtn.selected) {
            [weakself.model.imgs removeObjectAtIndex:indexPath.row];
            [weakself updateUI];
        }
    };
    CGSize size = CGSizeMake((SCREEN_WIDTH - 40), self.collection.frame.size.height - 40);
    cell.bounds = CGRectMake(0, 0, size.width, size.height);
    return  cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return  CGSizeMake((SCREEN_WIDTH - 40), self.collection.frame.size.height - 40);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return  UIEdgeInsetsMake(20, 20, 20, 20);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

@end

